from concurrent.futures import ThreadPoolExecutor
import subprocess
from multiprocessing import Process
from tools.mySpiders.startspider import start_spider
from module.man_hua import man_hua
from flask import Response, render_template
from flask import request
from module.man_hua.manhua_download_of_thread import DownloadOfThread, CreateIndexJson
from module.man_hua.manhua_works_index import create_manhua_works_index
import platform
from web_app import socketio
import re

import ctypes

goDll=ctypes.CDLL("./tools/myGo/myGo.dll")

# 线程池
executor = ThreadPoolExecutor(2)
WORK_JIE_G = "下载中"
WORK_NAME = " "
WORK_DICT = dict()  # 作品结果字典
# 下载作品


def down_works(spider_name, name1:str, url1):
    global WORK_DICT
    try:
        # 判断系统
        py = "python"
        my_os = platform.system()
        if my_os == "Linux":
            py = "python3"
        # 开始爬虫
        if spider_name == "se8":
            subprocess.run(
                py + " startspider.py" + " se8_call" + " " + name1 + " " + url1,
                cwd="./tools/mySpiders",
                shell=True,
            )
        elif spider_name == "aikanhanman":
            subprocess.run(
                py + " startspider.py" + " aikanhanman_call" + " " + name1 + " " + url1,
                cwd="./tools/mySpiders",
                shell=True,
            )
            # p=Process(target=start_spider,args=("aikanhanman_call",name1, url1))
            # p.start()
            # p.join()
        elif spider_name == "mhua5":
            subprocess.run(
                py + " startspider.py" + " mhua5_call" + " " + name1 + " " + url1,
                cwd="./tools/mySpiders",
                shell=True,
            )
            # p=Process(target=start_spider,args=("mhua5_call",name1, url1))
            # p.start()
            # p.join()
        elif spider_name == "aman5":
            subprocess.run(
                py + " startspider.py" + " aman5_call" + " " + name1 + " " + url1,
                cwd="./tools/mySpiders",
                shell=True,
            )
        else:
            WORK_DICT[name1] = "下载失败"
            return
        # 爬取完毕，开始下载
        JSON_FILE_NAME = "./static/man_hua/spider_data/" + name1 + ".json"
        DIE_NAME = "./static/man_hua/works/" + name1
        DownloadOfThread(JSON_FILE_NAME, DIE_NAME,10).Start()
        # goDll.C_Down_work_of_thread(ctypes.c_char_p(JSON_FILE_NAME.encode('utf-8')),ctypes.c_char_p(DIE_NAME.encode('utf-8')),ctypes.c_int(20))
        CreateIndexJson(DIE_NAME)

        # 创建模板
        f1 = open("./static/man_hua/manhua_0_index.html", "r", encoding="utf-8")
        htmlMoBan = f1.read()
        f1.close()

        fileName = DIE_NAME + "/" + "0_index.html"
        f2 = open(fileName, "w", encoding="utf-8")
        f2.write(htmlMoBan)
        f2.close()

        # 创建作品索引
        create_manhua_works_index("./static/man_hua/works/")
        WORK_DICT[name1] = "下载完成"
    except Exception as e:
        WORK_DICT[name1] = "下载失败"
        print(e)
    print(name1 + WORK_DICT[name1])


@man_hua.route("/add_works")
def add_works():
    return render_template("/man_hua/add_works.html")


@man_hua.route("/add_works/submit")
def add_works_submit():
    global WORK_NAME, WORK_JIE_G
    spider_name = request.args.get("spider_name")
    name1 = request.args.get("name")
    # 过滤非法字符
    name1 = re.sub('[\\/:.*?"<>|]', '', name1)
    url1 = request.args.get("url")
    WORK_NAME = name1
    WORK_JIE_G = "下载中"
    if not (name1 is None or url1 is None or spider_name is None):
        WORK_DICT[WORK_NAME] = WORK_JIE_G
        executor.submit(down_works, spider_name, name1, url1)
    return render_template("/man_hua/add_works.html")


@socketio.on("man_hua_down_jie_guo", namespace="/man_hua/add_works/steam")
def on_steam(msg):
    str1 = []
    for i in WORK_DICT:
        str1.append({"name": i, "jie_g": WORK_DICT[i]})
    for key in list(WORK_DICT.keys()):
        if not WORK_DICT[key] == "下载中":
            del WORK_DICT[key]

    # print(msg)
    socketio.emit("man_hua_down_jie_guo", str1, namespace="/man_hua/add_works/steam")
